<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Strings in PHP</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="PHP, learn PHP, programming, language, strings">
<meta name="description" content="In this part of the PHP tutorial, we cover PHP strings.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Strings in PHP</h1>

<p>
In this part of the PHP programming tutorial, we will work with string data in more detail.  
</p>

<div class="center">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* top_horizontal */
google_ad_slot = "3327173442";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
Strings are the most important data types in computer languages. 
That is why we dedicate a whole chapter to working with strings in PHP. 
</p>


<h2>String literals</h2>

<p>
A <b>string literal</b> is the notation for representing a string value within the text 
of a computer program.
In PHP programming language, strings can be created with single quotes,  double quotes or using
the heredoc syntax.
</p>


<pre class="code">
&lt;?php

$a = "PHP";
$b = 'PERL';

echo $a, $b;

?&gt;
</pre>

<p>
In this code example, we create two strings and assign them to $a, $b variables. We print them
with the echo command. The first string is created with the double quote delimiters, the second
one with single quotes. 
</p>


<p>
The next example will create a string with a heredoc syntax. 
The heredoc preserves the line breaks and other whitespace (including indentation) in the text. 
The heredoc is created with &lt;&lt;&lt; followed by a delimiting identifier, followed, 
starting on the next line, by the text to be quoted, 
and then closed by the same identifier on its own line. The closing identifier 
must not be indented. It can only contain alphanumeric characters and underscores, 
and must start with a non-digit character or underscore.
</p>

<pre class="code">
&lt;?php

$str = &lt;&lt;&lt;TEXT
"That is just as I intended." Vautrin said. "You know quite well what
you are about. Good, my little eaglet! You are born to command, you
are strong, you stand firm on your feet, you are game! I respect you."
TEXT;

echo $str, "\n";

?&gt;
</pre>

<p>
The semicolon is optional.
</p>

<pre class="code">
echo "PHP " . "language"; # prints PHP language
</pre>

<p>
PHP uses the dot (.) operator to concatenate two strings. 
</p>

<h2>Escape characters</h2>

<p>
An <b>escape character</b> is a single character designated to invoke an alternative 
interpretation on immediately subsequent characters in a character sequence. (Wikipedia)

</p>

<pre class="code">
php &gt; echo "   bbb\raaa";
aaabbb
</pre>

<p>
The carriage return \r is a control character for end of line return to beginning of line.
</p>

<pre class="code">
&lt;?php
echo "Incompatible, it don't matter though\n'cos someone's bound to hear my cry\n";
echo "Speak out if you do\nYou're not easy to find\n";
?&gt;
</pre>

<p>

The new line is a control character, which begins a new line of text. 
</p>

<pre>
$ php strophe.php 
Incompatible, it don't matter though
'cos someone's bound to hear my cry
Speak out if you do
You're not easy to find
</pre>


<pre>
echo "Towering\tinferno"; # Towering    inferno
</pre>

<p>
The horizontal tab puts a space between text. 
</p>

<pre>
"Johnie's dog"
'Johnie\'s dog'
</pre>

<p>
Single and double quotes can be nested. Or in case we use only single quotes, 
we can use the backslash to escape the default meaning of a single quote. 
</p>

<pre class="code">
&lt;?php

$text = "
\"That is just as I intended.\" Vautrin said. \"You know quite well what
you are about. Good, my little eaglet! You are born to command, you
are strong, you stand firm on your feet, you are game! I respect you.\"
";

echo $text;
?&gt;
</pre>

<p>
In this example, we have a multiline text, which includes direct speech. 
The double quotes are escaped with the backslash character. 
</p>

<pre class="code">
php &gt; $var = 233;
php &gt; echo "$var";
233
php &gt; echo "\$var is $var";
$var is 233
</pre>

<p>
The dollar sign $ has also a special meaning in PHP. It denotes a variable. 
If a variable is used inside a string, it is interpolated, e.g. the value of the variable
is used. To echo a variable name, we escape the $ character \$.
</p>

<h2>Operations on strings</h2>

<p>
PHP has a large number of useful useful built-in functions that 
can be used for working with strings. 
</p>

<pre>
echo strlen("Eagle"); # prints 5
echo strtoupper("Eagle"); # prints EAGLE
echo strtolower("Eagle"); # prints eagle
</pre>

<p>
Here we use three functions. The <code>strlen()</code> function returns a number of characters in the
string. The <code>strtoupper()</code> converts characters to uppercase letters, the 
<code>strtolower()</code> converts characters to lowercase letters.
</p>


<pre class="code">
&lt;?php

$sentence = "There are 22 apples";

$alphas = 0;
$digits = 0;
$spaces = 0;

$length = strlen($sentence);

for ($i = 0; $i < $length; $i++)
{

    $c = $sentence[$i];
    if (ctype_alpha($c)) $alphas++;
    if (ctype_digit($c)) $digits++;
    if (ctype_space($c)) $spaces++;

}


echo "There are $length characters.\n";
echo "There are $alphas alphabetic characters.\n";
echo "There are $digits digits.\n";
echo "There are $spaces spaces.\n";

?&gt;
</pre>

<p>
In our example, we have a string sentence. We calculate the absolute number of characters, number of alphabetic characters,
digits and spaces in the sentence. To do this, we use functions: <code>strlen()</code>, 
<code>ctype_alpha()</code>, <code>ctype_digit()</code> and <code>ctype_space()</code>.
</p>

<pre>
$ php letters.php 
There are 19 characters.
There are 14 alphabetic characters.
There are 2 digits.
There are 3 spaces.
</pre>

<p>
Next, we cover the <code>substr()</code> function.
</p>

<pre>
echo substr("PHP language", 0, 3); # prints PHP
echo substr("PHP language", -8); # prints language
</pre>

<p>
The function returns a part of a string. The first parameter is the specified string.
The second parameter is the start of the substring. The third parameter is optional.
It is the length of the returned substring. Default is to the end of the string.
</p>

<p>
The <code>str_repeat()</code> function repeats a string a specified 
number of times.
</p>

<pre class="code">
&lt;?php

echo str_repeat("#", 18);
echo "\nProject Neurea\n";
echo "Priority high\n";
echo "Security maximum\n";
echo str_repeat("#", 18);
echo "\n";

?&gt;
</pre>

<p>
We use the str_repeat() function to create two lines of the # character. 
</p>

<pre>
$ php repeat.php 
##################
Project Neurea
Priority high
Security maximum
##################
</pre>

<p>
In the next example, we will randomly modify a string.
</p>

<pre class="code">
&lt;?php

$string = "ZetCode";

echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";
echo str_shuffle($string), "\n";

?&gt;
</pre>

<p>
The <code>str_shuffle()</code> randomly shuffles a string.
</p>

<pre>
$ php shuffle.php 
CteZeod
teZCdeo
ZteoCed
odCteZe
oCdetZe
eedtCZo
edCetoZ
</pre>


<p>
The <code>explode()</code> function is used to split a string
into parts. It returns an array of split string parts. 
</p>

<pre class="code">
&lt;?php

$text = "Rastignac heard him in dazed bewilderment; 
he could not find a word in reply. Just then Goriot 
came in, and Bianchon and a few of the
boarders likewise appeared.";

$sentences = explode(".", $text);

echo $sentences[0];
echo $sentences[1];

?&gt;
</pre>

<p>
We have two sentences. Each sentence is ended with a full stop. 
</p>

<pre class="explanation">
 $sentences = explode(".", $text);
</pre>

<p>
Here we split the text with the explode() function. The function will cut a string
into pieces, whenever it finds the dot (.) character.  
</p>

<pre class="code">
&lt;?php

echo "Ajax Amsterdam" . " - " . "Inter Milano " . "2:3\n";
echo "Real Madridi" . " - " . "AC Milano " . "3:3\n";
echo "Dortmund" . " - " . "Sparta Praha ". "2:1\n";

?&gt;
</pre>

<p>
We concatenate strings with the dot operator. 
</p>

<pre>
$ php teams1.php
Ajax Amsterdam - Inter Milano 2:3
Real Madridi - AC Milano 3:3
Dortmund - Sparta Praha 2:1
</pre>

<p>
The output does not look very good. We will change it so that it looks better. 
</p>

<pre class="code">
&lt;?php

$teams = array( 
      array("Ajax Amsterdam", "Inter Milano"),
      array("Real Madrid", "AC Milano"),
      array("Dortmund", "Sparta Praha")
);

$results = array("2:3", "3:3", "2:1");

$i = 0;

foreach ($teams as $team) {
    echo str_pad($team[0], 14);
    echo str_pad("-", 3, " ", STR_PAD_BOTH);
    echo str_pad($team[1], 14);
    echo str_pad($results[$i], 3, " ", STR_PAD_LEFT);
    echo "\n";
    $i++;
}
?&gt;
</pre>

<p>
We improve the output format with the <code>str_pad()</code> function. It adds
a specified string (in our case a space) to the left of the string, to the right or to both sides.  
</p>

<pre>
$ php teams2.php 
Ajax Amsterdam - Inter Milano  2:3
Real Madrid    - AC Milano     3:3
Dortmund       - Sparta Praha  2:1
</pre>

<p>
We manage to give a more nicely formatted output.
</p>


<h2>String formatting</h2>

<p>
String formatting or string interpolation is dynamic putting of various values into a string. 
</p>

<pre class="code">
&lt;?php

printf("There are %d oranges and %d apples in the basket.\n", 12, 32);

?&gt;
</pre>

<p>
We use the %d formatting specifier. The d character says, we are 
expecting an integer. After the string, we put a modulo operator and an 
argument. In this case an integer value.  
</p>

<pre>
$ php fruits.php 
There are 12 oranges and 32 apples in the basket.
</pre>

<p>
In the next example, we will interpolate a float and a string value. 
</p>

<pre class="code">
&lt;?php

printf("Height: %f %s\n", 172.3, "cm");

?&gt;
</pre>

<p>
The formatting specifier for a float value is <b>%f</b> and for a string <b>%s</b>.
</p>

<pre>
$ php height.php 
Height: 172.300000 cm
</pre>

<p>
We might not like the fact, that the number in the previous example 
has 6 decimal places by default. We can control the number of the decimal 
places in the formatting specifier. 
</p>

<pre class="code">
&lt;?php

printf("Height: %.1f %s\n", 172.3, 'cm');

?&gt;
</pre>

<p>
The decimal point followed by an integer controls the number of decimal 
places. In our case, the number will have exactly one decimal place. 
</p>

<pre>
$ php height2.php 
Height: 172.3 cm
</pre>

<p>
The following example shows other formatting options. 
</p>

<pre class="code">
&lt;?php

# hexadecimal
printf("%x\n", 300);

# octal
printf("%o\n", 300);

# scientific
printf("%e\n", 300000);

?&gt;
</pre>

<p>
The first interpolation works with hexadecimal numbers. The <b>x</b> character will format the number 
in hexadecimal notation. The <b>o</b> character shows the number in 
octal format. The <b>e</b> character will show the number in scientific format. 
</p>

<pre>
$ php formatting.php 
12c
454
3.000000e+5
</pre>

<p>
The next example will print three columns of numbers. 
</p>

<pre class="code">
&lt;?php

foreach (range(1,11) as $num) {
    echo $num , " ", $num*$num, " ",
         $num*$num*$num, "\n";
}

?&gt;
</pre>

<p>
The numbers are left justified and the output look terrible. 
</p>

<pre>
$ php columns.php 
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
11 121 1331
</pre>

<p>
To correct this, we use the width specifier. The width specifier defines the minimal 
width of the object. If the object is smaller than the width, it is filled with spaces. 
</p>

<pre class="code">
&lt;?php

foreach (range(1,11) as $num) {
    printf("%2d %3d %4d\n", $num, $num*$num, $num*$num*$num);
}

?&gt;
</pre>

<p>
Now the output looks OK. 2 says that the first column will be 2 characters wide. 
</p>

<pre>
$ php columns2.php 
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
11 121 1331
</pre>


<p>
This part of the PHP tutorial covered strings. 
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 24, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

